//
//  CZPublishViewController.swift
//  项目框架
//
//  Created by yang on 16/3/5.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
let holderString = "屌丝和白富美果然很配额！"

class CZPublishViewController: UIViewController ,UITextViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        setupTextView()
        setupToolBar()
        
        //给键盘添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardDidChangeFrameNotification, object: nil)
 }

  //设置nav
    private func setupNav(){
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        //默认发布按钮不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        //标题
        let title = UILabel(frame: CGRectMake(0,0,200,40))
        
        //换行
        title.numberOfLines = 0
        
        //文字居中
        title.textAlignment = .Center
        
        let str = "发布微博\n\(CZUserViewModel.shareInstance.model?.screen_name ?? "")"
        
        // NSAttributedString -- 这个是不可变的,我们要修改属性的话,需要用到
        //NSMutableAttributedString
        
        let attribute = NSMutableAttributedString(string: str)
        
        //添加属性
        
        //修改”发布微博“的属性
         attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        //修改下面的名字的属性
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.orangeColor()], range:NSMakeRange(4, str.characters.count - 4))
        
        title.attributedText = attribute
        
        navigationItem.titleView = title
        
    }
    //懒加载
    private lazy var textView:CZTextView = CZTextView()
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    //添加一个textView
    private func setupTextView(){
    
        view.addSubview(textView)
        //textView的大小等于屏幕的大小
        textView.frame = view.frame
        
        textView.holderString = holderString
        
        textView.font = UIFont.systemFontOfSize(15)
        
        //实现textview的代理，当内容改变的时候做操作
        textView.delegate = self
        
        //滑动textview让键盘消失
        textView.alwaysBounceVertical = true
        
        textView.keyboardDismissMode = .OnDrag
    }
    
    //添加toolbar
    private func setupToolBar(){
    
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        //定义一个数值,来接受 items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
        
            //自定义button
            let button = UIButton(type: UIButtonType.Custom)
            
            //设置button的属性和方法
            button.setImage(UIImage(named: setting["imageName"]!), forState: UIControlState.Normal)
            
            //高亮状态图片
            let imageName = setting["imageName"]!
            
            button.setImage(UIImage(named: "\(imageName)__highlighted"), forState: UIControlState.Highlighted)
            
            //button的大小一定要设置
            button.sizeToFit()

            //添加方法
            if let action = setting["action"]{
            
                 // 当你添加方法的时候 -> "loadData" 注意  "loadData"并不代表他是字符串
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
                
                //赋值
           }
            let item = UIBarButtonItem(customView: button)
                
                // item 添加到toolBar,一定要自己定义一个数组
                items.append(item)
                
               //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil))
            
            
            
        }
        //移除最后多出来的一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        //添加视图
        view.addSubview(toolBar)
        //添加约束（否则不显示图片）
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            
            make.height.equalTo(40)
        }
    }
    //MARK:--选择图片的方法
    @objc private func choosePicture(){
        printLog("显示图片")
    }
    //MARK:--显示表情
    @objc private func inputEmoticon(){
        printLog("显示表情")
    }
    
    //通知的方法
    func changeToolBarFrame(noti:NSNotification){
    
        //分析这样一个问题,我们什么时候知道键盘弹出,什么时候退出
        if let info = noti.userInfo{
            
            let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            
            //如果Y等于屏幕高度则消失
            if endFrame?.origin.y == UIScreen.mainScreen().bounds.height{
            
                printLog("退出")
            }else{
            
            //否则弹出
                printLog("弹出")
                
                
            }
        
        }
        
    }
    //按钮的点击事件  @objc 运行机制，能让系统运行的时候找到这个方法
    @objc  private func dismiss(){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    @objc  private func publish(){
    
    
    }
}

//textView的代理方法
extension CZPublishViewController{

    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText(){
        
        //不显示占位符
            self.textView.holderString = ""
        
        }else{
            
            //显示
            self.textView.holderString = holderString
        
        }
        //重写draw方法需要重绘
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
